package pers.yurwisher.rubick.oauth2.service;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author yq 2021/4/15 17:49
 * @description ClientDetailsServiceImpl aouth2 client 获取
 */
@Component
@RequiredArgsConstructor
public class CustomClientDetailsService implements ClientDetailsService{

    private final RedisTemplate<String,Object> redisTemplate;
    /**
     * 通过 clientId 获取 client实例
     * @param clientId clientId
     * @return client实例
     * @throws ClientRegistrationException
     */
    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        // todo 从缓存获取
        BaseClientDetails clientDetails = new BaseClientDetails();

        clientDetails.setClientId("nacos");
        // 这个客户端秘钥和密码一样存BCryptPasswordEncoder加密后的接口，具体看定义的加密器
        clientDetails.setClientSecret("8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92");

        List<String> autoApproveScopes = new ArrayList<>(1);
        autoApproveScopes.add("server");
        // 自动批准作用于，授权码模式时使用，登录验证后直接返回code，不再需要下一步点击授权
        clientDetails.setAutoApproveScopes(autoApproveScopes);

        List<String> scopes = new ArrayList<>(1);
        scopes.add("all");
        clientDetails.setScope(scopes);

        // 资源id列表，需要注意的是这里配置的需要与ResourceServerConfig中配置的相匹配
        List<String> resourceIds = new ArrayList<>();
        resourceIds.add("rubick-oauth2");
        clientDetails.setResourceIds(resourceIds);

        List<String> grantTypes = new ArrayList<>(5);
        grantTypes.add("password");
        grantTypes.add("refresh_token");
        grantTypes.add("authorization_code");
        grantTypes.add("implicit");
        grantTypes.add("mobile");
        clientDetails.setAuthorizedGrantTypes(grantTypes);

        Set<String> sets = new HashSet<>(1);
        sets.add("http://www.baidu.com");
        clientDetails.setRegisteredRedirectUri(sets);

        clientDetails.setAuthorities(new ArrayList<>());
        // 设置accessToken和refreshToken的时效，如果不设置则使tokenServices的配置的
        clientDetails.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(2));
        clientDetails.setRefreshTokenValiditySeconds((int)TimeUnit.DAYS.toSeconds(30));

        return clientDetails;
    }
}
